<?php

namespace App\Http\Controllers\Admin;

use App\Models\Member as MemberModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Member extends Controller
{
    //会员列表
    public function all()
    {
        $members = MemberModel::orderBy('created_at', 'desc')->paginate(10);
        $viewData = [
            'members' => $members
        ];
        return view('admin.member.list', $viewData);
    }

    //会员添加
    public function add()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['username', 'password', 'nickname', 'email']);
            $result = (new MemberModel)->add($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '添加成功',
                    'url' => url('admin/memberlist')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        return view('admin.member.add');
    }

    //会员编辑
    public function edit()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['id', 'oldpass', 'password', 'nickname']);
            $result = (new MemberModel)->edit($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '修改成功',
                    'url' => url('admin/memberlist')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        $memberInfo = MemberModel::find(request('id'));
        $viewData = [
            'memberInfo' => $memberInfo
        ];
        return view('admin.member.edit', $viewData);
    }

    //会员删除
    public function del()
    {
        $memberInfo = MemberModel::with('articles', 'comments')->find(request('id'));
        foreach($memberInfo->articles as $vo) {
            $vo->delete();
        }
        foreach($memberInfo->comments as $vo) {
            $vo->delete();
        }
        $result = $memberInfo->delete();
        if ($result) {
            $msg = [
                'code' => 1,
                'msg' => '删除成功',
                'url' => url('admin/memberlist')
            ];
        }else {
            $msg = [
                'code' => 0,
                'msg' => '删除失败'
            ];
        }
        return $msg;
    }
}
